package servlet;

import service.WxService;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * Created by Administrator on 2019/1/21.
 */

//    接收消息和事件推送的
public class WxServlet extends javax.servlet.http.HttpServlet {
    protected void doPost(javax.servlet.http.HttpServletRequest request , javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
/*
System.out.println("post");
ServletInputStream is = request.getInputStream();
byte[] b = new byte[1024];
int len;
StringBuilder sb = new StringBuilder();
while ((len=is.read(b))!=-1){
sb.append(new String(b,0,len));
}
//打印出数据包
System.out.println(sb.toString());
*/
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        Map<String, String> requestMap = WxService.parseRequest(request.getInputStream());
        System.out.println(requestMap);

        //准备回复的数据包

//   演示     String resXml =  "<xml><ToUserName><![CDATA["+requestMap.get("FromUserName")+"]]></ToUserName><FromUserName><![CDATA["+requestMap.get("ToUserName")+"]]></FromUserName><CreateTime>"+System.currentTimeMillis()/1000+"</CreateTime><MsgType><![CDATA[text]]></MsgType><Content><![CDATA[this is success]]></Content><MsgId>1234567890123456</MsgId></xml>";

        String resXml = WxService.getResponse(requestMap);
        System.out.println(resXml);
        PrintWriter out = response.getWriter();
        out.print(resXml);
        out.flush();
        out.close();

    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        String signature = request.getParameter("signature") ;
        String timestamp = request.getParameter("timestamp") ;
        String nonce = request.getParameter("nonce") ;
        String echostr = request.getParameter("echostr") ;
//        System.out.println(signature);
//        System.out.println(timestamp);
//        System.out.println(nonce);
//        System.out.println(echostr);
//        System.out.println("get");
        if (WxService.check(signature, timestamp, nonce)){
            System.out.println("=======请求校验成功======" + echostr);
            //原样返回echostr参数
            PrintWriter out = response.getWriter();
            out.print(echostr);
            out.flush();
            out.close();
        }
    }
}
